import { promises as fs } from 'fs';
import path = require('path');
import { inputPathToOutputPath } from './path';

// 通过文件路径收集目录路径
export function collectDirsPathByFilesPath(filesPath: string[]) {
  let dirsPath: string[] = [];

  // 获取全部目录
  filesPath.forEach(filePath => {
    const outputFilePath = inputPathToOutputPath(filePath);
    const dirPath = path.dirname(outputFilePath);
    dirsPath.push(dirPath);
  });

  // 过滤重复目录
  dirsPath = [...new Set(dirsPath)];

  // 过滤父级目录
  dirsPath = dirsPath.filter(currentDirPath => {
    return !dirsPath.some(otherDirPath => (otherDirPath.startsWith(currentDirPath) && otherDirPath !== currentDirPath));
  })

  return dirsPath;
}

// 通过目录路径创建目录
export async function mkdirByDirsPath(dirsPath: string[]) {
  for await (const dirPath of dirsPath) {
    await fs.mkdir(dirPath, { recursive: true });
  }
}
